package com.quyunshuo.module.home.util

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import java.io.IOException

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

class SettingsDataStore(private val context: Context) {

    // 定义键
    companion object {
        val VIBRATION_ENABLED = booleanPreferencesKey("vibration_enabled")
        // 添加更多设置键...
    }

    // 保存震动设置
    suspend fun saveVibrationSetting(enabled: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[VIBRATION_ENABLED] = enabled
        }
    }

    // 获取震动设置（返回Flow）
    val vibrationSetting: Flow<Boolean> = context.dataStore.data
        .catch { exception ->
            if (exception is IOException) {
                emit(emptyPreferences())
            } else {
                throw exception
            }
        }
        .map { preferences ->
            preferences[VIBRATION_ENABLED] ?: true // 默认值设为true
        }
    suspend fun getVibrationSettingOnce(): Boolean {
        return context.dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                preferences[VIBRATION_ENABLED] ?: true
            }
            .first() // 取Flow的第一个值，即当前值
    }
}